package ltd.sshine.tracking.security.context;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken;

public class GlobalContext {
    public static Long getUserId() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication instanceof JwtAuthenticationToken jwtAuthenticationToken) {
            return (Long) jwtAuthenticationToken.getTokenAttributes().get("userId");
        }
        throw new RuntimeException("用户未登录");
    }

    /**
     * 获取公司id
     * @return 公司id
     */
    public static Long getCompanyId() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication instanceof JwtAuthenticationToken jwtAuthenticationToken) {
            return (Long) jwtAuthenticationToken.getTokenAttributes().get("companyId");
        }
        throw new RuntimeException("用户未登录或未加入公司");
    }
    /**
     * 获取当前公司用户id
     * @return 公司id
     */
    public static Long getCompanyUserId() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication instanceof JwtAuthenticationToken jwtAuthenticationToken) {
            return (Long) jwtAuthenticationToken.getTokenAttributes().get("companyUserId");
        }
        throw new RuntimeException("用户未登录或未加入公司");
    }

    /**
     * 获取公司id，未加入或者未登录返回null
     * @return 公司id
     */
    public static Long getCompanyIdOrNull() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication instanceof JwtAuthenticationToken jwtAuthenticationToken) {
            return (Long) jwtAuthenticationToken.getTokenAttributes().get("companyId");
        }
       return null;
    }
}
